<?php

/**
 * This is the model class for table "{{category}}".
 *
 * The followings are the available columns in table '{{category}}':
 * @property integer $id
 * @property string $name
 * @property integer $parent_id
 * @property integer $level

 *
 * The followings are the available model relations:
 * @property Category $parent
 * @property Category[] $categories
 */
class Category extends CActiveRecord
{

	private static $_categories;
        
        private static $_allCategories;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Category the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{category}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		$rules = array(
			array('name', 'required'),
			array('parent_id', 'numerical', 'integerOnly'=>true),
                        array('level', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>128),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name, parent_id, level', 'safe', 'on'=>'search'),
		);
                
                foreach (Yii::app()->params->otherLanguages as $k => $v) {
                        $rules[] = array('name_'.$k, 'safe');
                }
                return $rules;
	}
        
        public function behaviors() {
            return array(
                'ml' => array(
                'class' => 'application.components.behaviors.MultilingualBehavior',
                'primaryLang' => Yii::app()->language, //your main language
                'languages' => Yii::app()->params->otherLanguages, //your translated languages
                'localizedAttributes' => array('name'),
                'relName1' => 'i18nCategory',
                'relName2' => 'multilang',
                ),
            );
        }
        
        public function localized() {
            $this->getDbCriteria()->mergeWith(array(                      
                'with'=>array(
                    'i18nCategory'=>array(),
                    //'parent'=>array('scopes'=>array('localizedSecond')),
                    //'categories'=>array('scopes'=>array('localizedSecond')),
                ),
            ));
            return $this;
        }
        
        public function localizedSecond() {
            $this->getDbCriteria()->mergeWith(array(                      
                'with'=>array(
                    'i18nCategory'=>array(),
                ),
            ));
            return $this;
        }

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'parent' => array(self::BELONGS_TO, 'Category', 'parent_id'),
			'categories' => array(self::HAS_MANY, 'Category', 'parent_id'),
                        
                        'i18nCategory' => array(self::HAS_MANY, 'CategoryLang', 'category_id', 'on'=>"i18nCategory.lang_id='".Yii::app()->language."'", 'index'=>'lang_id'),
                        //'i18nCategory2' => array(self::HAS_MANY, 'CategoryLang', 'category_id', 'on'=>"i18nCategory2.lang_id='".Yii::app()->language."'", 'index'=>'lang_id'),
                        'multilang' => array(self::HAS_MANY, 'CategoryLang', 'category_id', 'index' => 'lang_id'),
		);
	}
        
        public function __get($name) {
            try { return parent::__get($name); } 
            catch (CException $e) {
                if ($this->hasLangAttribute($name)) return $this->getLangAttribute($name);
                else throw $e;
            }                                                     
        }

        public function __set($name, $value) {
            try { parent::__set($name, $value); } 
            catch (CException $e) {
                if ($this->hasLangAttribute($name)) $this->setLangAttribute($name, $value);
                else throw $e;
            }                                     
        }

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => 'Română',
			'parent_id' => 'Părintele',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('parent_id',$this->parent_id);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	public static function allCategories()
	{
		if(!isset(self::$_categories))
			self::loadItems();
		return self::$_categories;
	}
        
        private static function loadItems()
	{
		self::$_categories=array();
		$models=self::model()->localized()->findAll();
                
                $prefixes = array();
                $prefixes[0] = '';
                $prefixes[1] = '---';
                $prefixes[2] = '------';
                
		foreach($models as $model) {
                    self::$_categories[$model->id] = $prefixes[$model->level].$model->name;
                }
	}
	
	public function getUrl()
	{
            //$actionName = Yii::app()->controller->action->name;
            //if ($actionName == 'news')
            return Yii::app()->createUrl("post/index", array("category" => $this->id));
            //return Yii::app()->createUrl("post/".$actionName, array("category" => $this->id));

	}
        
        public static function categoriesByLevel($level) {
            if(!isset(self::$_allCategories))
            {
                self::$_allCategories=array();
                $models = self::model()->localized()->findAll();
                
                foreach($models as $model)
                    self::$_allCategories[$model->level][$model->id]=$model->name;
            }
            return self::$_allCategories[$level];
        }
        
        public function getCategoriesByParent($parent_id) {
            return $this->localized()->findAll(array(
                        'condition'=>'parent_id='.$parent_id,
		));
        }
	

}